﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using iTextSharp.text.pdf;
using iTextSharp.text;

namespace MalikSumLib.Utilities
{
    public class iTextHeaderFooter : PdfPageEventHelper
    {

        //public override void OnEndPage(PdfWriter writer, iTextSharp.text.Document document)
        //{
        //   // base.OnEndPage(writer, document);
        //}

        protected PdfTemplate total;
        protected PdfTemplate copyRight;
        protected BaseFont helv;
        private bool settingFont = false;


        public override void OnOpenDocument(PdfWriter writer, Document document)
        {
            copyRight = writer.DirectContent.CreateTemplate(300, 150);

            total = writer.DirectContent.CreateTemplate(100, 100);
            total.BoundingBox = new Rectangle(0, 0, 100, 100);
            helv = BaseFont.CreateFont(BaseFont.HELVETICA, BaseFont.WINANSI, BaseFont.NOT_EMBEDDED);
        }

        public override void OnEndPage(PdfWriter writer, Document document)
        {
            document.Open();
            PdfContentByte cb = writer.DirectContent;
            cb.SaveState();

            string text = "Page " + writer.CurrentPageNumber + " of ";
            float adjust = helv.GetWidthPointKerned(text, 12);
            float textBase = document.Bottom - 20;
            float textHeader = document.Top + 30;
            float textSize = 12; //helv.GetWidthPoint(text, 12);
            cb.BeginText();
            cb.SetFontAndSize(helv, 12);
            if ((writer.CurrentPageNumber % 2) == 1)
            {
                cb.SetTextMatrix(document.Right - 75, textBase);
                cb.ShowText(text);
                cb.EndText();
                cb.AddTemplate(total, document.Right - 75 + adjust, textBase);
            }
            else
            {

                cb.SetTextMatrix(document.Right - 75, textBase);
                cb.ShowText(text);
                cb.EndText();
                cb.AddTemplate(total, document.Right - 75 + adjust, textBase);
            }
            float adjustHeader = helv.GetWidthPointKerned(" Copy Right Global4Web.com ", 12) / 2;
            cb.AddTemplate(copyRight, document.Left + (document.Right / 2) - adjustHeader, textHeader);
            cb.RestoreState();

        }

        public override void OnCloseDocument(PdfWriter writer, Document document)
        {
            copyRight.BeginText();
            copyRight.SetFontAndSize(helv, 10);
            copyRight.ShowText(" Copy Right Global4Web.com ");
            copyRight.EndText();

            total.BeginText();
            total.SetFontAndSize(helv, 12);
            total.SetTextMatrix(0, 0);
            int pageNumber = writer.CurrentPageNumber - 1; //(writer.PageNumber - 1)/2;
            total.ShowText(Convert.ToString(pageNumber));
            total.EndText();
        }






    }
}
